// pages/mall/goodsDetail/index.js
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import { exceedMessageTip, isAllowAddCart } from '../../../../utils/hooks';
import { getDatetime, getElement } from '../../../../utils/util';
const $api = require('../../../../request/api').API;
const app = getApp();
const animation = wx.createAnimation();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsId: '', //商品goodsId
    goodsInfo: null,
    goodsImages: [],
    nums: 0,
    beeperBtnId: '',
    showSpec: '',
    collect: '', //1是收藏，0是取消
    name: '',
    variantId: '',
    mainImage: '',
    shopCartPosition: '',
    addAnimation: '',
    showDot: false,
    dotClientX: '',
    dotClientY: '',
    discount: '',
    activeDiscount: '',
    activeNums: 0,
    menuBtnTop: app.globalData.menuBtnTop,
    menuBtnHeight: app.globalData.menuBtnHeight,
    formData: {
      show: false,
      val: null
    },
    balanceInfo: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    const { goodsId, beeperBtnId, orderSource, sourceId, btnName, open, date } = options;
    this.open = open; // open存在表示是从首页过来的，需要显示购物车或者是显示规格选择
    if (goodsId) {
      this.setData({
        goodsId,
        beeperBtnId: Number(beeperBtnId)
      });
      await this.getGoodsInfo();
    }
    const { balanceInfo } = this.data;
    orderSource && (balanceInfo.orderSource = orderSource);
    sourceId && (balanceInfo.sourceId = sourceId);
    btnName && (balanceInfo.btnName = btnName);
    this.setData({
      beeperId: app.globalData['btnList.beeperId'] || app.globalData['details.beeperId'] || '',
      balanceInfo
    });
    this.getStyle();
    if (open) {
      const { variantState, goodsType, huskFlag, saleState, stock } = this.data.goodsInfo;
      if (saleState !== 2 || !stock) return;
      if (variantState == 2 || goodsType == 2 || huskFlag) {
        // 选规格
        this.selectSpec();
      } else {
        // 添加购物车
        await this.addNum({ detail: {}, currentTarget: { dataset: {} } });
      }
      this.open = false;
      delete app.globalData['btnList.e'];
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  getStyle() {
    wx.nextTick(() => {
      getElement('#balance>>>.shop-cart-img').then(res => {
        this.setData({
          shopCartPosition: res[0]
        });
      });
    });
  },
  // 返回
  back() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 通过商品id来获取对应的数组索引，不存在就返回-1
  getIndexById(arr, id, prop = 'id') {
    let tempIndex = -1;
    arr.find((item, index) => {
      if (item[prop] == id) {
        tempIndex = index;
        return true;
      }
    });
    return tempIndex;
  },
  // 获取商品信息
  async getGoodsInfo() {
    let params = {
      id: this.data.goodsId
    };
    const res = await $api.getGoodsInfo(params);
    let data = res.data.data;
    // 给图片添加一个最大的宽度
    // data.describes = data.describes.replace(/\<img/gi, '<img  style="max-width:320px;height:auto"')
    let mainImage = data.goodsImages.find(item => item.mainFlag).url;
    this.setData({
      goodsInfo: data,
      goodsImages: data.goodsImages,
      name: data.name,
      variantId: data.variantId,
      collect: data.collect,
      mainImage,
      discount: parseFloat(((data.salePrice / data.price) * 10).toFixed(2))
    });

    this.getShopNum();
    this.activeTime();
  },
  // 点击连接
  handleTagATap(e) {
    wx.navigateTo({
      url: '/subcontract/person/pages/h5Page/index?url=' + encodeURIComponent(e.detail.href)
    });
    // "https://h5.kanglailab.com/nucleicLeaving"
  },
  // 预览图片
  imagePreview(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: this.data.goodsImages.map(item => item.url),
      current: url
    });
  },
  // 获取本地存储购物车存储当前商品的数量
  getShopNum() {
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    let nums = 0;
    shopCartList.find(item => {
      if (item.goodsId == this.data.goodsId) {
        nums = nums + item.nums;
      }
    });
    this.setData({
      nums
    });
    this.timeOut(this.data.goodsId);
  },
  // 新增
  async addNum(e) {
    const { goodsInfo } = this.data;
    const goods = e.detail.goodsId ? e.detail : goodsInfo;
    const { goodsId } = goods;
    const shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    const eventId = app.globalData['btnList.eventId'];
    if (!isAllowAddCart({ goods, eventId, shopCartList })) return;
    // if(isDockingEvent(eventId)){
    //   if(eventId==18){
    //     // 18的时候保存doctorId
    //     app.globalData['dock.doctorId'] = doctorId
    //   }
    //   if(exceedMessageTip(eventId,shopCartList)) return
    // }
    // if(isDeferConfirmWay(businessConfirmWay,shopCartList)) return
    // if(app.globalData["btnList.eventId"]==18){
    //   app.globalData['dock.doctorId'] = doctorId
    //   if(shopCartList&&shopCartList.length>0) return Toast.fail("只能挂号一个")
    // }
    if (this.timeOut(goodsId)) return;
    this.activeTime();
    if (e.detail.goodsId) {
      this.setData({
        nums: goodsId == this.data.goodsId ? this.data.nums + e.detail.nums : this.data.nums
      });
    } else {
      // 全局添加一个variantId
      app.globalData['btnList.variantId'] = goodsInfo.variantId;
      if (this.data.beeperId && goodsInfo.relationFlag && !this.data.nums) {
        this.setData({
          showSpec: true
        });
        return;
      }
      if (await this.judgeShowForm(e)) return;
      this.data.formData.show = false;
      this.setData({
        formData: this.data.formData
      });

      // 动画,open存在的时候不能显示动画而是直接显示购物车
      if (this.open) {
        this.selectComponent('#balance').setData({
          showShopCart: true
        });
      } else {
        this.addAni(e.touches[0]);
      }
      this.setData({
        nums: this.data.nums + 1
      });
    }

    // 这里是判断子子组件的增加是否执行
    if (!e.detail.flag) {
      e.flag = true;
      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId || this.data.variantId;
      let nums = e.detail.nums || 1;
      let obj = Object.assign(
        { ...goodsInfo },
        {
          nums: nums,
          id: this.data.beeperBtnId,
          name: this.data.name,
          mainImage: this.data.goodsImages[0].url
        },
        e.detail
      );
      this.selectComponent('#balance').addNum(e, obj);
    }
  },
  addCart() {
    this.addNum(this.event);
  },
  shopCartChangeNum(e) {
    const { goodsInfo } = this.data;
    const { goodsId, nums } = e.detail;
    if (goodsInfo.goodsId != goodsId) return;
    this.setData({
      nums
    });
  },
  // 判断是否需要显示弹框
  async judgeShowForm(e) {
    const { attrMark, serverId, goodsId, thirdClassifyId, businessId, doctorId, date } = this.data.goodsInfo;
    if (!attrMark) return false;
    // 获取本地缓存的表单数据,如果不存在就需要获取数据并显示表单组件
    let formList = wx.getStorageSync('formList');
    formList = formList ? JSON.parse(formList) : [];
    const index = formList.findIndex(item => item.id == goodsId + '-' + serverId);
    if (index != -1) return false;
    let res = await $api.getFormItemInfo({ serverId, goodsId, thirdClassifyId, businessId });
    res = res.data.data || [];
    const { formData } = this.data;
    formData.val = {
      id: goodsId + '-' + serverId,
      name: res[0].goodsName || res[0].serverName,
      introduce: res[0].introduce,
      list: res
    };
    formData.show = true;
    this.setData({
      formData
    });
    this.event = e;
    return true;
  },
  // 添加动画
  addAni({ clientX, clientY }) {
    const { top, right } = this.data.shopCartPosition;
    this.setData({
      showDot: true,
      dotClientX: clientX - 4,
      dotClientY: clientY - 8
    });
    setTimeout(() => {
      animation
        .top(clientY - 25)
        .left(clientX - 60)
        .step({ duration: 100 })
        .top(top)
        .left(right - 12)
        .step({ duration: 100, timingFunction: 'ease-in' });
      this.setData({
        addAnimation: animation.export()
      });
      setTimeout(() => {
        this.setData({
          showDot: false,
          addAnimation: null
        });
      }, 200);
    });
  },
  // 清空数量
  clear() {
    this.setData({
      nums: 0
    });
  },
  // 减少
  subNum(e) {
    const goodsId = e.detail.goodsId || this.data.goodsId;
    if (this.timeOut(goodsId)) return;
    this.activeTime();
    if (e.detail.goodsId) {
      this.setData({
        nums: e.detail.goodsId == this.data.goodsId ? this.data.nums - 1 : this.data.nums
      });
    } else {
      this.setData({
        nums: this.data.nums - 1
      });
    }
    // 这里是判断子组件的subNum是否执行
    if (!e.detail.flag) {
      e.flag = true;
      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId || this.data.variantId;
      this.selectComponent('#balance').subNum(e);
    }
  },
  // 超时
  timeOut(id) {
    let { goodsId, goodsInfo, nums } = this.data;
    let goods = goodsInfo;
    if (id != goodsId) {
      return false;
    }
    if (!goods.goodsHours || (goods.goodsHours && !goods.goodsHours.length)) return;
    const res = goods.goodsHours.some(item => {
      let time = new Date();
      let begin = new Date();
      let end = new Date();
      const arr = item.beginHours.split(':').map(item => Number(item));
      const arr2 = item.endHours.split(':').map(item => Number(item));
      begin.setHours(arr[0]);
      begin.setMinutes(arr[1]);
      end.setHours(arr2[0]);
      end.setMinutes(arr2[1]);
      return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
    });
    if (!res) {
      // 售罄之后改变状态同时清空购物车里面售罄的该数据
      goods.saleState = 0;
      this.setData({
        goodsInfo,
        nums: id == goodsId ? 0 : nums
      });
      this.selectComponent('#balance').timeOut(goodsId);
      // 上一页也需要这样
      const page = getCurrentPages().at(-2);
      page.timeOut(goodsId);
      return true;
    } else {
      return false;
    }
  },
  //需要判断是不是活动时间
  activeTime() {
    const { goodsInfo } = this.data;
    if (!goodsInfo.active) return;
    let { beginDate, endDate, activePrice, maxNum } = goodsInfo.active;
    beginDate = getDatetime(beginDate).getTime();
    endDate = getDatetime(endDate).getTime();
    let nowDate = new Date().getTime();
    if (nowDate > beginDate && nowDate < endDate) {
      this.setData({
        activeDiscount: parseFloat(((activePrice / goodsInfo.price) * 10).toFixed(2)) || 0.01,
        activeNums: maxNum
      });
    } else {
      this.setData({
        activeDiscount: '',
        activeNums: 0
      });
    }
  },
  // 输入商品数量
  // numChange(e){
  //   let nums = 0
  //   if(e.detail.goodsId){
  //     // 组件调用此方法
  //     if(e.detail.goodsId!=this.data.goodsId) return
  //     nums = e.detail.nums||0
  //     let sameNum = listData.filter(item=>{
  //       return item.goodsId == e.detail.goodsId &&item.variantId !=e.detail.id
  //     }).map(item=>item.nums).reduce((a,b)=>a+b,0)
  //     nums = sameNum+nums
  //     this.setData({
  //         nums,
  //     })
  //   }else{
  //     // 自身调用此方法
  //       this.setData({
  //           nums:Number(e.detail.value)
  //       })
  //   }
  //   if(!e.detail.flag){
  //       e.flag=true
  //       e.currentTarget.dataset.id = e.detail.id||this.data.variantId
  //       let nums = e.detail.nums||this.data.nums
  //       console.log(e,this.data.nums)
  //       this.selectComponent("#balance").numChange(e,nums)
  //   }
  // },
  // 选择规格
  selectSpec() {
    const { goodsId, name, doctorId, goodsInfo } = this.data;
    console.log(goodsId);
    if (goodsInfo.specDisplayType == 1) {
      // 跳转到规格页面
      wx.navigateTo({
        url: '/subcontract/home/pages/goodsSpec/index?goodsId=' + goodsId
      });
      return;
    }
    const eventId = app.globalData['btnList.eventId'];
    if (exceedMessageTip({ eventId })) return;
    if (this.timeOut(goodsId)) return;
    this.setData({
      showSpec: true,
      name
    });
  },
  // 电话咨询
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.goodsInfo.businessPhone,
      fail: err => {
        Toast.fail('拨打失败');
      }
    });
  },
  // 收藏
  collectGoods() {
    let state = this.data.collect ? 0 : 1;
    let params = {
      collectType: 1,
      state,
      goodsId: this.data.goodsId
    };

    $api.setCollect(params).then(res => {
      this.setData({
        collect: state
      });
      if (state) {
        wx.showToast({
          title: '收藏成功'
        });
      }
      let pages = getCurrentPages();
      let page = pages[pages.length - 2];
      let temp = page.data.listData.find(item => {
        return item.goodsId == this.data.goodsId;
      });
      if (temp) {
        temp.collect = state;
        page.setData({
          listData: page.data.listData
        });
      }
    });
  },
  // 图片预览
  previewImage() {
    if (!this.data.goodsInfo) return;
    wx.previewImage({
      current: this.data.goodsInfo.images, // 当前显示图片的 http 链接
      urls: [this.data.goodsInfo.images] // 需要预览的图片 http 链接列表
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});
